package com.hg.util.export;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import com.google.gson.Gson;
import com.hg.util.db.IDao;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class ToolGeneratorFile extends IDao
{
    Gson gson = new Gson();
    
   
    /**
     * @param root	数据
     * @param ftl_dir	ftl目录,相对于com.hg.util.export;
     * @param ftl_file	ftl模板文件名,vo.ftl
     * @param outFile	导出的路径	"WebRoot/WEB-INF/ftl/"+app_name+"/"+module_str+"/"+module+".ftl";
     * @throws IOException
     * @throws TemplateException
     */
    public void writeToFile(Map<String, Object> root,String ftl_dir,String ftl_file,String outFile) throws IOException, TemplateException{
    	//1.创建配置实例Cofiguration  
        Configuration cfg = new Configuration();  
        cfg.setDefaultEncoding("utf-8");
        cfg.setOutputEncoding("utf-8");
        //根据类来定位
        cfg.setClassForTemplateLoading(ToolGeneratorFile.class, ftl_dir);
    	
    	
    	//建立数据模型（Map）  
        String module_str = (String) root.get("module");
        String app_name = (String) root.get("app_name");
        if("admin".equals(app_name)){
        	app_name="admins";
        }
        String url =outFile;
        CreateFileUtil.createFile(url);
        
        //获取模板（template）  
        Template template = cfg.getTemplate(ftl_file+".ftl"); 
        
        //com.hg.admin.db.tool
        FileOutputStream fos = new FileOutputStream(url);
        Writer out = new OutputStreamWriter(fos,"UTF-8");
        
        template.process(root, out);
        out.flush();  
        out.close();
    }
}
